package is.ru.server;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * Created in IntelliJ IDEA.
 * Students: Jón Geir Sigurbjörnsson, Kristinn Helgi Hilmarsson, Jón Rúnar Arnarsson
 * Class: T-408-STNE, Stýrikerfi og netkerfi, 2011-1
 * Project: Programming assignment 3: HTTP web server
 * Date: 16.3.2011
 * Time: 20:17
 */

public class TCPRequestHandler implements Runnable
{
    Socket socket;

    static final byte[] EOL = {(byte) '\r', (byte) '\n'};

    public TCPRequestHandler(Socket socket)
    {
        this.socket = socket;

        // Make new threads
        Thread t = new Thread(this);
        t.start();
    }

    public void run()
    {
        BufferedReader bInput = null;
        PrintStream pOutput = null;
        try
        {
            try
            {
                // New stream to get the input
                bInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // New stream to print out the output
                pOutput = new PrintStream(socket.getOutputStream(), true);

                String line = bInput.readLine();
                if (line != null)
                {
                    System.out.println(line);
                    //Make new request
                    Request handleRequest = new Request(line);
                    String response = handleRequest.getResponse();

                    printHeaders(response, pOutput);
                    printBody(response, pOutput);
                }
            } finally // Close all the streams that were open
            {
                if (pOutput != null)
                    pOutput.close();
                if (bInput != null)
                    bInput.close();
                if (socket != null)
                    socket.close();
            }
        } catch (IOException e)
        {
            System.out.println("TCPRequestHandler IOException");
            e.printStackTrace();
        }
    }

    // Print the message to the body
    private void printBody(String message, PrintStream ps) throws IOException
    {
        ps.write(EOL);
        ps.print(message);
    }

    // Print info about the server to the header
    private void printHeaders(String message, PrintStream ps) throws IOException
    {
        ps.print("HTTP/1.0 200 OK");
        ps.write(EOL);
        ps.print("Server: JKN Java Server");
        ps.write(EOL);
        ps.print("Date: " + (new Date()));
        ps.write(EOL);
        ps.print("Content-length: " + message.length());
        ps.write(EOL);
        ps.print("Last Modified: " + new Date());
        ps.write(EOL);
        ps.print("Content-type: text/html");
        ps.write(EOL);
    }
}
